import requests
import logging
from bs4 import BeautifulSoup
import hashlib
from pathlib import Path
import time
from email.mime.text import MIMEText
import smtplib

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s')

CONFIG = {
    "url": "http://www.jtjyfw.net/NewList-108.aspx",
    "selector": "h6",
    "storage_file": "last_content.hash",
    "check_interval": 60,
    "smtp": {
        "host": "smtp.qq.com",  # QQ邮箱服务器
        "port": 465,  # SSL端口
        "user": "1571351926@qq.com",  # 你的QQ邮箱
        "password": "wpduxozxvjoijhaf",  # 邮箱授权码（不是密码）
        "from": "1571351926@qq.com",  # 必须与user相同
        "to": "2717301343@qq.com"  # 接收邮箱
    }
}


def get_page_content(url):
    """获取网页内容"""
    headers = {
        "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
    }
    try:
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()
        return response.text
    except requests.exceptions.RequestException as e:
        logging.error(f"请求页面失败: {str(e)}")
        return None


def extract_content(html, selector):
    """提取指定区域内容"""
    try:
        soup = BeautifulSoup(html, 'html.parser')
        target_element = soup.select_one(selector)
        return target_element.text.strip() if target_element else ""
    except Exception as e:
        logging.error(f"解析内容失败: {str(e)}")
        return ""


def get_content_hash(content):
    """生成内容哈希值"""
    return hashlib.md5(content.encode('utf-8')).hexdigest()


def load_last_hash():
    """读取上次保存的哈希值"""
    try:
        if Path(CONFIG['storage_file']).exists():
            with open(CONFIG['storage_file'], 'r') as f:
                return f.read().strip()
    except IOError:
        pass
    return None


def save_last_hash(hash_value):
    """保存最新哈希值"""
    try:
        with open(CONFIG['storage_file'], 'w') as f:
            f.write(hash_value)
    except IOError as e:
        logging.error(f"保存哈希值失败: {str(e)}")


def send_email_notification(subject, body):
    msg = MIMEText(body, 'plain', 'utf-8')
    msg['Subject'] = subject
    msg['From'] = CONFIG['smtp']['from']
    msg['To'] = CONFIG['smtp']['to']

    try:
        # 使用SMTP_SSL替代SMTP
        server = smtplib.SMTP_SSL(CONFIG['smtp']['host'],
                                  CONFIG['smtp']['port'])
        server.login(CONFIG['smtp']['user'], CONFIG['smtp']['password'])
        server.sendmail(CONFIG['smtp']['from'], [CONFIG['smtp']['to']],
                        msg.as_string())
        server.quit()
        logging.info("邮件通知已发送")
    except Exception as e:
        logging.error(f"发送邮件失败: {str(e)}")


def check_update():
    """执行一次更新检查"""
    logging.info("开始检查更新...")
    html = get_page_content(CONFIG["url"])
    if html is None:
        return
    # 提取关键内容
    current_content = extract_content(html, CONFIG['selector'])
    if not current_content:
        logging.warning("未提取到有效内容，请检查选择器配置")
        return
    # 生成哈希值
    current_hash = get_content_hash(current_content)
    last_hash = load_last_hash()
    # 比较哈希值
    if last_hash != current_hash:
        logging.info("检测到内容更新！")

        # 发送通知
        send_email_notification(subject="网站公告更新通知",
                                body=f"检测到内容变更，请查看：{CONFIG['url']}")
        
        # 保存新哈希值
        save_last_hash(current_hash)
    else:
        logging.info("内容未发生变化")


def main():
    # 初始化存储文件
    if not Path(CONFIG['storage_file']).exists():
        logging.info("首次运行，初始化存储文件...")
        check_update()  # 生成初始哈希值
        return

    # 启动定时检查循环
    while True:
        try:
            check_update()
        except Exception as e:
            logging.error(f"检查过程中发生未捕获异常: {str(e)}")

        time.sleep(CONFIG['check_interval'])


if __name__ == "__main__":
    main()
